/**
 * @(#)BaseController.java, 2018/2/6.
 * <p/>
 * Copyright 2018 Kerr Wang, Inc. All rights reserved.
 * KERRWANG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package org.wangzx.exercise.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModelException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author hzwangzuxiang(ahscwzx@163.com)
 */
public class BaseController {

    private static Set<Class> classSet;
    static {
        // 添加的静态方法Java的Class
        classSet = new HashSet<Class>();
        classSet.add(JSONArray.class);
        classSet.add(JSONObject.class);
    }

    public void setNoCache(HttpServletResponse response) {
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
    }

    /**
     * 构建ModelAndView，并加入公用的模型数据
     *
     * @param viewName
     *            视图
     */
    protected ModelAndView genModelAndView(String viewName) {
        ModelAndView mav = new ModelAndView(viewName);
        appendStaticMethod(mav);
        return mav;
    }

    /**
     * 构建ModelAndView，并加入公用的模型数据
     *
     * @param viewName
     *            视图
     * @param model
     *            模型数据
     * @return
     */
    protected ModelAndView genModelAndView(String viewName, Map<String, ?> model) {
        ModelAndView mav = new ModelAndView(viewName, model);
        appendStaticMethod(mav);
        return mav;
    }

    /**
     * 添加指定的Java对象的Static方法(附带返回当前时间)
     *
     * @param mv
     * @throws TemplateModelException
     */
    protected void appendStaticMethod(ModelAndView mv) {
        // 设置给FTL使用的对象
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        try {
            for (Class classItem: classSet)
                mv.addObject(classItem.getSimpleName(),
                        (TemplateHashModel) staticModels.get(classItem.getName()));
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
    }
}